package com.yifeng.repo.micro.service.server.engine.master.idx;

import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yifeng.repo.base.constant.BaseConstant;
import com.yifeng.repo.base.utils.redis.worker.RedisLockWorker;
import lombok.extern.slf4j.Slf4j;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;

/**
 * Created by daibing on 2023/9/28.
 */
@Slf4j
public class ServerEngineIdentifierGenerator implements IdentifierGenerator {
    private static final Long EXPIRE_SECONDS = 365 * 24 * 60 * 60L;

    /**
     * 机器标识位数
     */
    private final long workerIdBits = 5L;
    private final long datacenterIdBits = 5L;
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);

    /**
     * 雪花算法id生成
     */
    private final Sequence sequence;

    public ServerEngineIdentifierGenerator(String applicationName, RedisLockWorker redisLockWorker) {
        long datacenterId = getDatacenterId(maxDatacenterId);
        long workerIdByPid = getMaxWorkerIdByPid(datacenterId, maxWorkerId);
        long workerIdByRedis = getMaxWorkerIdByRedis(datacenterId, maxWorkerId, applicationName, redisLockWorker);
        this.sequence = new Sequence(workerIdByRedis, datacenterId);
        log.info("Initialization Sequence datacenterId:{}, workerId:{}, workerIdByPid:{}", datacenterId, workerIdByRedis, workerIdByPid);
    }

    @Override
    public Long nextId(Object entity) {
        return sequence.nextId();
    }

    /**
     * 数据标识id部分
     */
    private long getDatacenterId(long maxDatacenterId) {
        long id = 0L;
        try {
            NetworkInterface network = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
            if (null == network) {
                id = 1L;
            } else {
                byte[] mac = network.getHardwareAddress();
                if (null != mac) {
                    id = ((0x000000FF & (long) mac[mac.length - 2]) | (0x0000FF00 & (((long) mac[mac.length - 1]) << 8))) >> 6;
                    id = id % (maxDatacenterId + 1);
                }
            }
        } catch (Exception e) {
            log.info(" getDatacenterId: " + e.getMessage());
        }
        return id;
    }

    /**
     * 获取 maxWorkerId
     */
    private long getMaxWorkerIdByPid(long datacenterId, long maxWorkerId) {
        StringBuilder mpid = new StringBuilder();
        mpid.append(datacenterId);
        String name = ManagementFactory.getRuntimeMXBean().getName();
        if (StringUtils.isNotBlank(name)) {
            /*
             * GET jvmPid
             */
            mpid.append(name.split(StringPool.AT)[0]);
        }
        /*
         * MAC + PID 的 hashcode 获取16个低位
         */
        return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
    }

    private long getMaxWorkerIdByRedis(long datacenterId, long maxWorkerId, String applicationName, RedisLockWorker redisLockWorker) {
        String key = applicationName
                + BaseConstant.REDIS_SEPARATOR + "idWorker"
                + BaseConstant.REDIS_SEPARATOR + datacenterId;
        return redisLockWorker.incr(key, maxWorkerId, EXPIRE_SECONDS);
    }
}
